package com.daikin.ktmustwrite.ui.fragment.tree

import android.os.Bundle
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ConvertUtils
import com.daikin.ktmustwrite.R
import com.daikin.ktmustwrite.app.base.BaseFragment
import com.daikin.ktmustwrite.app.ext.*
import com.daikin.ktmustwrite.app.weight.recycleview.DefineLoadMoreView
import com.daikin.ktmustwrite.app.weight.recycleview.SpaceItemDecoration
import com.daikin.ktmustwrite.databinding.IncludeListBinding
import com.daikin.ktmustwrite.ui.adapter.AriticleAdapter
import com.daikin.ktmustwrite.viewmodel.request.RequestTreeViewModel
import com.daikin.ktmustwrite.viewmodel.state.TreeViewModel
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import kotlinx.android.synthetic.main.include_recyclerview.*


class PlazaFragment : BaseFragment<TreeViewModel, IncludeListBinding>() {

    private lateinit var loadsir:LoadService<Any>
    private val requestTreeViewModel:RequestTreeViewModel by viewModels()
    //recyclerview的底部加载view 因为要在首页动态改变他的颜色，所以加了他这个字段
    private lateinit var footView: DefineLoadMoreView

    private val articleAdapter: AriticleAdapter by lazy {
        AriticleAdapter(arrayListOf(), showTag = true)
    }

    override fun layoutId(): Int {
        return R.layout.include_list
    }

    override fun initView(savedInstanceState: Bundle?) {
        //状态页配置
        loadsir = loadServiceInit(swipeRefresh) {
            //点击重试时触发的操作
            loadsir.showLoading()
            requestTreeViewModel.getPlazaData(true)
        }
        recyclerView.init(LinearLayoutManager(context),articleAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, ConvertUtils.dp2px(8f)))
            footView=it.initFooter(SwipeRecyclerView.LoadMoreListener {
                requestTreeViewModel.getPlazaData(false)
            })
        }
        swipeRefresh.init {
            //触发刷新监听时请求数据
            requestTreeViewModel.getPlazaData(true)
        }
        articleAdapter.run {

        }

    }

    override fun lazyLoadData() {
        loadsir.showLoading()
        requestTreeViewModel.getPlazaData(true)
    }

    override fun createObserver() {
        requestTreeViewModel.plazaDataState.observe(viewLifecycleOwner, Observer {
            //设值 新写了个拓展函数，搞死了这个恶心的重复代码
            loadListData(it, articleAdapter, loadsir, recyclerView, swipeRefresh)
        })
    }
}